module.exports = app => {
    var express = require('express')
    var router = express.Router()
    const customer = require('../../models/customer')
    const order = require('../../models/Order')
    // const http = require('https')
     var request = require('request')
     var xmlreader = require("xmlreader")
     const crypto = require('crypto')
     const xml2js = require('xml2js')
     var jsonBuilder = new xml2js.Builder()// json->xml
     var xmlParser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true })// xml->json
     var xmlparser = require('express-xml-bodyparser');//引入
   
     //把金额转为分
    function getmoney(money){
        return parseFloat(money) * 100;
    }
    // // 随机字符串产生函数
    function randomString(len) {
        len = len || 32;
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        var maxPos = chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }


    router.get('/pays',async(req,res) => {
        // console.log(req.query)
        var datas = { appid:'wx3f8607ee708aaccb',
         body:req.query.body,
         mch_id:'1521320581',
         nonce_str: Math.random().toString(36).substr(2, 15),
         notify_url:'http://www.nj246.com:80/api/pays_url',
         openid:req.query.openid,
         out_trade_no:req.query.paySigns,
         spbill_create_ip:req.connection.remoteAddress.split(":")[3],
         total_fee:getmoney(0.01),
         trade_type:'JSAPI',
        //sign:getsign()
        }
        // console.log(datas)
        datas.sign =getsign(datas)
        datas = jsonBuilder.buildObject(datas)
        //需要保存的订单信息
        if(req.query.status == "待支付"){
            console.log("等待支付")
        }else{

             var time = new Date()
        var model = {
            cash_fee:req.query.cash_fee,
            goods_list:JSON.parse(req.query.goods_list),
            order_time:time,
            out_trade_no:req.query.paySigns,
            address:JSON.parse(req.query.address),
            beizhu:req.query.beizhu,
            way:req.query.way,
        }
            var id=await order.create(model)
            var _id=JSON.parse(JSON.stringify(id))._id
            var token=req.query.token
            await customer.updateOne({token:token},{$addToSet:{orders: _id}},(err)=>{
                if(err){
                    // console.log(err)
                } 
            }) 
        }
      
   //客户保存订单_id


// console.log("xml==="+datas)
request.post({
    url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
    method: "POST",
    json: true,
    headers: {
        "content-type": "application/json",
    },
    body: datas
}, async function (err, response, body) {
    // console.log("err=="+err)
    // console.log("status=="+response.statusCode)
    // console.log("body=="+body)
    if (!err && response.statusCode === 200) {
        let data = body
        
        xmlParser.parseString(data, function (err, result) {
            data = result
        })
        data = data.xml
        console.log(data)
        var packages='prepay_id='+data.prepay_id
        let backdata = await {
            appId: data.appid,
            nonceStr: randomString(32),
            package: packages,
            signType:'MD5',
            timeStamp: (parseInt((new Date()).getTime() / 1000)).toString()
           
        }
        if (!data.prepay_id) { return res.send({ code: 400, msg: '参数错误' }) }
        // console.log(backdata)
        backdata.sign = await getsign(backdata)
        // console.log("最终的值"+backdata.sign)
        res.send(backdata)
    }
    

})


    })


    router.post('/pays_url', xmlparser({ trim: false, explicitArray: false }),async(req,res) => {
        var jsonData = req.body.xml;
        console.log("pays_url=="+jsonData)
        if (jsonData.result_code == 'SUCCESS') {
            var key = "wSV7IfyOHUPYv1MOt8nHckEVOX7cGOhf";
    
            var stringA = "appid=" + jsonData.appid + "&bank_type=" + jsonData.bank_type + "&cash_fee=" + jsonData.cash_fee + "&fee_type=" + jsonData.fee_type +
                "&is_subscribe=" + jsonData.is_subscribe + "&mch_id=" + jsonData.mch_id + "&nonce_str=" + jsonData.nonce_str + "&openid=" +
                jsonData.openid + "&out_trade_no=" + jsonData.out_trade_no + "&result_code=" + jsonData.result_code + "&return_code=" +
                jsonData.return_code + "&time_end=" + jsonData.time_end + "&total_fee=" + jsonData.total_fee + "&trade_type=" +
                jsonData.trade_type + "&transaction_id=" + jsonData.transaction_id;
            var stringSignTemp = stringA + "&key=" + key;
            var sign = crypto.createHash('md5').update(stringSignTemp, 'utf8').digest('hex').toUpperCase();
            console.log("pays_url_sign="+sign)
            if (sign == jsonData.sign) {
                console.log('yes')
                var out_trade_no = jsonData.out_trade_no
                await order.updateOne({out_trade_no:out_trade_no},{$set: {status:"待配送"}}) //支付完成改变订单状态
                
                //json转xml
                var json2Xml = function (json) {
                    let _xml = '';
                    Object.keys(json).map((key) => {
                        _xml += `<${key}>${json[key]}</${key}>`
                    })
                    return `<xml>${_xml}</xml>`;
                }


                
                var sendData = {
                    return_code: 'SUCCESS',
                    return_msg: 'ok'
                }


                res.end(json2Xml(sendData))


            }
        }
            })



            
    //签名
  function getsign(datas){
         //按key值的ascii排序
    const keys = Object.keys(datas).sort();
    const temp = [];
    keys.forEach(v => {
        if (datas[v] && v !== 'sign') {
            temp.push(`${v}=${datas[v]}`);
        }
    });
    temp.push('key=wSV7IfyOHUPYv1MOt8nHckEVOX7cGOhf');// temp.push('key=');
    const ret = temp.join('&');
    // console.log("签名数据："+ret)
    //生成签名
    return crypto.createHash('md5').update(ret, 'utf8').digest('hex').toUpperCase();
  }

    app.use('/api',router)
}